<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/30
 * Time: 22:47
 */

namespace app\company\controller;


use app\common\model\BasicArea;
use app\common\model\SalesCompany;
use app\common\model\SuppliersCompany;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class Suppliers extends Admin
{
    /**
     * 获取公司列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);

        $model = new SuppliersCompany();
        $param = $this->getWhere();
        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->where($param)->order('create_time desc,id desc')->page($page,$limit)->select();
        foreach ($lst as $info){
            $info['address_area'] = str_replace(' ','',$info['address_area']);
            $info['address'] = $info['address_area'].$info['address_detail'];
        }
        return json_tab_msg($count,$page,$lst);
    }

    /**
     * 导出供货商列表
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function dataExport(){
        $param = $this->getWhere();
        $model = new SuppliersCompany();
        $order_lst = $model->where($param)->order('create_time desc,id desc')->select();
        $arr = [];
        foreach ($order_lst as $item) {
            $item['state'] = $item['state'] ==1 ?'关闭':'正常';
            $arr[] = $item;
        }
        $table_title = ['供货商名称','联系人','电话', '所在区域', '详细地址', '税率','服务品牌','服务截止时间','状态'];
        $table_value = ['suppliers_company_name','contact_person_name','contact_person_phone','address_area','address_detail','tax_rate', 'service_brand', 'due_time','loss_assessor', 'user_name','user_phone','user_company_name', 'common','state'];
        //导出
        $filename = '供货商信息' . date('Ymd');
        export_excle($order_lst, $table_title, $table_value, $filename);
    }

    /**
     * 获取单个供货商信息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo(){
        $id = input('id');
        $showCity = input('showCity',0);
        $model = new SuppliersCompany();
        $info = $model->where(['id'=>$id])->find();
        if($info){
            $address_area = explode(' ',$info['address_area']);
            if($showCity){
                $areaC = new Area();
                $info['province'] = isset($address_area[0])?$address_area[0]:'';
                $info['city'] = isset($address_area[1])?$address_area[1]:'';
                $info['district'] = isset($address_area[2])?$address_area[2]:'';
                $info['city_list'] = $areaC->getAreaList($info['city']);
                $info['district_list'] = $areaC->getAreaList($info['district']);
            }
            $info['password'] = '';
        }
        json_return_code($info);
    }

    /**
     * 查询参数
     * @return array
     */
    private function getWhere(){
        $state = input('state','');
        $due_date = input('due_date','');
        $words = input('words','','trim');
        $param = array();
        if($state || $state !== ''){
            $param['state'] = $state;
        }
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['due_time'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }
        if($words){
            $param['suppliers_company_name|contact_person_name|contact_person_phone|address_area|address_detail|service_brand'] = ['like','%'.$words.'%'];
        }
        return $param;
    }

    /**
     * 新增修改公司
     * @return \think\response\Json
     */
    public function modifyCompany(){
        $id = input('id');
        $data = $this->trimParam();
        if($data['password']){
            $data['password'] = md5($data['password']);
        }else{
            unset($data['password']);
        }
        $data['service_brand'] = $data['service_brand']?str_replace('，',',',$data['service_brand']):'';
        $model = new SuppliersCompany();
        if($id){
            $data['id'] = $id;
            $data['update_time'] = date('Y-m-d H:i:s');
            $result = $this->validate($data,'SuppliersCompany.save');
            if ($result !== true) json_return_code('',$result,201);
            $res = $model->allowField(true)->isUpdate(true)->save($data,array('id'=>$id));
            $msg = '修改';
            $company_id = $id;
            addLog('修改供应商信息');
        }else{
            $data['create_time'] = date('Y-m-d H:i:s');
            $result = $this->validate($data,'SuppliersCompany.add');
            if ($result !== true) json_return_code('',$result,201);
            $res = $model->allowField(true)->save($data);
            $msg = '添加';
            $company_id = $model->id;
            addLog('添加供应商信息');
        }
        if($res !== false){
            $info = $model->where('id',$company_id)->find();
            json_return_code($info,$msg.'成功');
        }else{
            json_return_code('',$msg.'失败', '201');
        }
    }

    /**
     * 修改供货商状态
     * @return void
     */
    public function changeState()
    {
        $id = input('id');
        $data['state'] = input('state');
        $data['update_time'] = date('Y-m-d H:i:s');
        $model = new SuppliersCompany();
        if($model->isUpdate(true)->save($data,['id'=>$id]) !== false){
            addLog('修改供货商状态');
            json_return_code();
        }else{
            json_return_code('','操作失败',201);
        }
    }
    /**
     * 删除
     */
    public function del(){
        $id = input('id');
        $model = new SuppliersCompany();
        //1 参数验证是否合法
        if (empty($id)){
            json_return_code('',"公司ID不能为空！请检查",'201');
        }
        $model::destroy($id);
        addLog('删除供货商信息');
        json_return_code('','删除成功');
    }
}